<script setup lang="ts">
import { mergeProps, ref } from 'vue';
import { ElCard } from 'element-plus';
import { pick } from 'lodash-es';

import ProTable from './ProTable.vue';
import { ProForm, TProFormProps } from '../../form';
import type { TProTable } from './ProTable.vue';

const tableKeys = [
  'title',
  'columns',
  'showHeaderBar',
  'footerFixed',
  'tableProps',
  'hiddenFooter',
] as const;

const formKeys = [
  'col',
  'gutter',
  'align',
  'formItems',
  'resetText',
  'confirmText',
  'cancelText',
  'confirmProps',
] as const;

type TProTablePlusProps = TProTable &
  Partial<Omit<TProFormProps, 'model' | 'loading'>> & {
    search?: TProFormProps['model'];
    // 表单
    formProps?: any;

    // 简洁模式，即没有ElCard包裹
    concise?: boolean;
  };

const props = withDefaults(defineProps<TProTablePlusProps>(), {
  showHeaderBar: true,
  confirmText: '查询',
  // @ts-expect-error
  confirmProps: {
    plain: true,
  },
  formProps: {
    footer: true,
  },
});

defineEmits<{
  submit: [];
  reset: [];
  refresh: [];
}>();

const form = ref<any>();
defineExpose({ form });
</script>

<template>
  <component
    v-if="formItems"
    :is="concise ? 'div' : ElCard"
    :class="{ 'mb-3': !concise }"
    body-style="padding-bottom: 0"
  >
    <ProForm
      ref="form"
      v-bind="mergeProps(pick(props, formKeys), formProps || {})"
      size="medium"
      :formItems="formItems"
      :loading="loading"
      :model="search"
      :footer="{ col: 0 }"
      @submit="$emit('submit')"
      @reset="$emit('reset')"
    >
      <slot name="form" />
    </ProForm>
  </component>

  <ProTable
    v-bind="(mergeProps($attrs, pick(props, tableKeys)) as any)"
    stripe
    size="large"
    :list="list"
    :loading="loading"
    :concise="concise"
    :pagination="pagination"
    @refresh="$emit('refresh')"
  >
    <slot />

    <template #title>
      <slot name="title" :search="search" />
    </template>

    <template #headerExtra>
      <slot name="headerExtra" />
    </template>

    <template #footer>
      <slot name="tableFooter" />
    </template>
  </ProTable>
</template>
